﻿using FaceppSDK;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;
using Wechat.API.Filter;
using Wechat.Domain;
using Wechat.Manager;
using Wechat.Util.Image;
using Wechat.Util.ParmsConfig;
using Wechat.Util.TuLin;
using Wechat.Util.WechatUtil;

namespace Wechat.API.Controllers
{
    [RoutePrefix("api/even"), UnUserAuthorize]
    public class EvenController : ApiController
    {
        public IWechatLogManager WechatLogManager { get; set; }
        public IMemberInfoManager MemberInfoManager { get; set; }
        public IReplyMsgManager ReplyMsgManager { get; set; }

        /// <summary>
        /// 微信请求
        /// </summary>
        [Route("wechat"), HttpPost, HttpGet]
        public void WechatEven()
        {
            var context = System.Web.HttpContext.Current;

            string postString = string.Empty;
            if (context.Request.HttpMethod.ToUpper() == "POST")
            {
                using (Stream stream = context.Request.InputStream)
                {
                    Byte[] postBytes = new Byte[stream.Length];
                    stream.Read(postBytes, 0, (Int32)stream.Length);
                    postString = Encoding.UTF8.GetString(postBytes);

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(postString);
                    WechatXmlMsg xmlMsg = WechatMsgUtil.GetExmlMsg(doc);

                    try
                    {
                        switch (xmlMsg.MsgType)
                        {
                            case "text"://文本消息
                                TextCase(context, xmlMsg);
                                break;
                            case "event"://关注
                                EventCase(context, xmlMsg);
                                break;
                            case "voice":

                                break;
                            case "image":
                                ImageCase(context, xmlMsg);
                                break;
                            default:

                                break;
                        }
                    }
                    catch (Exception)
                    {

                    }
                    finally
                    {
                        //记录微信传入接口日志
                        WechatLog log = new WechatLog();
                        log.CreateTime = DateTime.Now;
                        log.LogType = 0;
                        log.Direction = "I";
                        log.XmlMsg = postString;
                        log.ToUserName = xmlMsg.ToUserName;
                        log.FromUserName = xmlMsg.FromUserName;
                        log.MsgType = xmlMsg.MsgType;
                        log.CreateTimeSpan = xmlMsg.CreateTime;
                        log.Content = xmlMsg.Content;
                        log.EventName = xmlMsg.EventName;
                        log.PicUrl = xmlMsg.PicUrl;
                        WechatLogManager.Insert(log);
                    }

                }
            }
            else
            {
                new AuthUtil().Auth(context);//微信验证
            }
        }

        #region 发送文本消息 +  TextCase(XmlElement root)
        private void TextCase(HttpContext context, WechatXmlMsg xmlMsg)
        {
            string text = xmlMsg.Content;
            string msg = "";
            var isAnswer = true;//是否会话，
            msg = ReplyMsgManager.GetReplyMsgByRecive(xmlMsg.Content);
            if (string.IsNullOrWhiteSpace(msg))
            {
                #region 如果数据库不存在该回复，则进行默认回复
                if (text == "你好" || text == "北京仲软" || text == "关注有礼")
                {
                    if (text == "你好")
                    {
                        msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎您加入仲软大家庭！");
                    }
                    else if (text == "北京仲软")
                    {
                        msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "<a href=\"http://m.pmscloud.com.cn/index.jsp\">点击了解</a>");
                    }
                    else if (text == "关注有礼")
                    {
                        msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "<a href=\"http://hd.lvjia168.net/zrwx/MemberInfoNew.aspx?openid=ovll_xD87J43m7xYQRCiiwKSChcI\">点击进入</a>");
                    }
                    else
                    {
                        msg = WechatMsgUtil.CreateTextMsg(xmlMsg, TuLingUtil.GetTulingMsg(text));
                    }
                }
                else
                {
                    if (text.Contains("t"))
                    {
                        text = text.Replace("t", "");
                        msg = WechatMsgUtil.CreateTextMsg(xmlMsg, TuLingUtil.GetTulingMsg(text));
                    }
                    else
                    {
                        isAnswer = WechatLogManager.HasMsgLogByOpenId(xmlMsg.FromUserName);
                        if (isAnswer)
                        {
                            msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎您加入仲软大家庭！\r\n请点击\"了解我们\"体验龙云PMS。\r\n请点击\"关注有礼\"参与有奖互动。\r\n请点击\"精彩回顾\"浏览往期好文。\r\n请您持续关注我们，惊喜连连、精彩不断！ 或者你想和机器人聊天请回复格式：t+你好（例如：t我饿了）");
                        }
                        else
                        {
                          
                        }
                    }
                }
                #endregion
            }
            else
            {
                msg = WechatMsgUtil.CreateTextMsg(xmlMsg,msg);
            }
            if (isAnswer)
            {
                context.Response.Write(msg);
                context.Response.Flush();
            }
            

        }
        #endregion

        #region 操作关注消息 EventCase EventCase(WechatXmlMsg xmlMsg)
        private void EventCase(HttpContext context, WechatXmlMsg xmlMsg)
        {
            string returntext = string.Empty;
            //创建会员
            MemberInfoManager.CreateMemberInfoByOpenId(xmlMsg.FromUserName);
            switch (xmlMsg.EventName)
            {
                case "subscribe"://关注消息
                    returntext = EvenSubscribeCase(xmlMsg);
                    break;
                case "unsubscribe"://取消关注
                    returntext = EvenUnsubscribeCase(xmlMsg);
                    break;
                case "location":
                    returntext = EvenLocationCase(xmlMsg);
                    break;
                case "click":
                    returntext = EvenClickCase(xmlMsg);
                    break;
                default:

                    break;
            }
            context.Response.Write(returntext);
            context.Response.Flush();
        }

        /// <summary>
        /// 关注时回复消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <returns></returns>
        private string EvenSubscribeCase(WechatXmlMsg xmlMsg)
        {
            //发送消息
            var returntext = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎您加入仲软大家庭！\r\n请点击\"了解我们\"体验龙云PMS。\r\n请点击\"关注有礼\"参与有奖互动。\r\n请点击\"精彩回顾\"浏览往期好文。\r\n请您持续关注我们，惊喜连连、精彩不断！ 或者你想和机器人聊天请回复格式：t+你好（例如：t我饿了）");
            return returntext;
        }

        /// <summary>
        /// 取消关注时回复消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <returns></returns>
        private string EvenUnsubscribeCase(WechatXmlMsg xmlMsg)
        {
            //发送消息
            var returntext = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎下次光临");
            return returntext;
        }

        /// <summary>
        /// 发送位置时回复消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <returns></returns>
        private string EvenLocationCase(WechatXmlMsg xmlMsg)
        {
            //发送消息
            var returntext = WechatMsgUtil.CreateTextMsg(xmlMsg, "定位已获取");
            return returntext;
        }

        /// <summary>
        /// 发送位置时回复消息
        /// </summary>
        /// <param name="xmlMsg"></param>
        /// <returns></returns>
        private string EvenClickCase(WechatXmlMsg xmlMsg)
        {
            //发送消息
            var returntext = WechatMsgUtil.CreateTextMsg(xmlMsg, "定位已获取");
            return returntext;
        }

        #endregion

        #region 发送声音消息 + void VoiceCase(XmlElement root)
        private void VoiceCase(HttpContext context, WechatXmlMsg xmlMsg)
        {
            string text = xmlMsg.Content;
            string msg = "";

            #region 如果数据库不存在该回复，则进行默认回复
            if (text == "你好" || text == "北京仲软" || text == "关注有礼")
            {
                if (text == "你好")
                {
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎您加入仲软大家庭！");
                }
                else if (text == "北京仲软")
                {
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "<a href=\"http://m.pmscloud.com.cn/index.jsp\">点击了解</a>");
                }
                else if (text == "关注有礼")
                {
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "<a href=\"http://hd.lvjia168.net/zrwx/MemberInfoNew.aspx?openid=ovll_xD87J43m7xYQRCiiwKSChcI\">点击进入</a>");
                }
                else
                {
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, TuLingUtil.GetTulingMsg(text));
                }
            }
            else
            {
                if (text.Contains("t"))
                {
                    text = text.Replace("t", "");
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, TuLingUtil.GetTulingMsg(text));
                }
                else
                {
                    msg = WechatMsgUtil.CreateTextMsg(xmlMsg, "欢迎您加入仲软大家庭！\r\n请点击\"了解我们\"体验龙云PMS。\r\n请点击\"关注有礼\"参与有奖互动。\r\n请点击\"精彩回顾\"浏览往期好文。\r\n请您持续关注我们，惊喜连连、精彩不断！ 或者你想和机器人聊天请回复格式：t+你好（例如：t我饿了）");
                }
            }
            #endregion

            context.Response.Write(msg);
            context.Response.Flush();

        }
        #endregion

        #region 发送图片消息 + void ImageCase(XmlElement root)
        private FaceService fs = new FaceService(ParmsConfigUtil.FaceAppId, ParmsConfigUtil.FaceAppSecret);
        public void ImageCase(HttpContext context, WechatXmlMsg xmlMsg)
        {
            string picUrl = xmlMsg.PicUrl;
            var mapPath = context.Server.MapPath(ParmsConfigUtil.ImgCaseUrl);
            //web图片保存到服务器
            var picPath = ImageUtil.SaveImageFromWeb(picUrl, mapPath, Guid.NewGuid().ToString());
            //face++取点
            DetectResult res = fs.Detection_Detect(picUrl);
            //初始化文件流
            Bitmap bmp = new Bitmap(mapPath + picPath);
            //画点
            bmp = ImageUtil.DrawRectangleInPicture(bmp, res, Color.Red, 1, DashStyle.Solid);
            var imgPath = Guid.NewGuid().ToString() + ".jpg";
            //保存图片
            bmp.Save(mapPath + imgPath, ImageFormat.Jpeg);
            //返回图片消息
            string msg = WechatMsgUtil.CreateImageMsg(xmlMsg, ParmsConfigUtil.WebSiteUrl + ParmsConfigUtil.ImgCaseUrl + imgPath);
            context.Response.Write(msg);
            context.Response.Flush();

        }
        #endregion
    }
}
